package com.lungle.warmdiary.app.view.me.fragment;

import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.text.Html;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

import com.nostra13.universalimageloader.core.ImageLoader;
import com.lungle.warmdiary.R;
import com.lungle.warmdiary.app.AppContext;
import com.lungle.warmdiary.app.api.exception.ApiErrorCode;
import com.lungle.warmdiary.app.api.exception.ApiErrorHelper;
import com.lungle.warmdiary.app.api.exception.ApiException;
import com.lungle.warmdiary.app.api.remote.ApiFactory;
import com.lungle.warmdiary.app.base.BaseActivity;
import com.lungle.warmdiary.app.base.BaseFragment;
import com.lungle.warmdiary.app.base.BaseSubscriber;
import com.lungle.warmdiary.app.model.Result;
import com.lungle.warmdiary.app.model.event.MediaChangeEvent;
import com.lungle.warmdiary.app.model.request.WechatPost;
import com.lungle.warmdiary.app.model.response.AddressPicker;
import com.lungle.warmdiary.app.model.response.MediaAccount;
import com.lungle.warmdiary.app.model.response.Tag;
import com.lungle.warmdiary.app.model.response.User;
import com.lungle.warmdiary.app.ui.dialog.CommonDialog;
import com.lungle.warmdiary.app.utils.UIHelper;
import com.umeng.analytics.MobclickAgent;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import cn.qqtheme.framework.picker.DatePicker;
import cn.qqtheme.framework.picker.OptionPicker;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;


/**
 * 微信账号编辑或新增
 */
public class MediaAddResultFragment extends BaseFragment {
    private static final String MEDIA_ADD_RESULT_SCREEN = "media add result screen";

    public static final int REQUEST_INDUSTRY = 0x0000;
    public static final int REQUEST_INTEREST = 0x0001;
    public static final int REQUEST_FRIEND = 0x0010;
    public static final int REQUEST_WID_CHANGE = 0x0011;
    public static final int REQUEST_WECHAT_NICKNAME_CHANGE = 0x0100;
    public static final int REQUEST_WECHAT_ICON = 0x0101;


    public static final int ACTION_UPDATE = 1;
    public static final int ACTION_CREATE = 2;


    public static final int RESULT_OK = 1;
    @Bind(R.id.tv_friend_tip)
    TextView mTvFriendTip;


    private View mRlUserIcon;
    private View mRlFriendIcon;
    private View mRlNickname;
    private View mRlWid;
    private View mRlBirth;
    private View mRlSex;
    private View mRlRealarea;
    private View mRlIndustryClass;
    private View mRlTags;
    private ImageView mIvUser;
    private TextView mTvNickname;
    private ImageView mIvFriend;
    private TextView mTvWid;
    private TextView mTvRealarea;
    private TextView mTvSex;
    private TextView mTvBirth;
    private TextView mTvIndustryClass;
    private TextView mTvTags;
    private Button mBtnSave;

    private MediaAccount mMediaAccount;


    //    private List<Tag> interestTags;
//    private Tag industryTag;
    private AddressPicker mAddressPicker;
    private int action;
    private boolean isEditable = true;
    private boolean isEditableALL = true;
    private ArrayList<AddressPicker.Province> mProvinces;


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_media_add_result, container, false);
        ButterKnife.bind(this, view);
        initData();
        initView(view);
        return view;
    }


    @Override
    public void initData() {
        mMediaAccount = (MediaAccount) getArguments().getSerializable("media_account");
        action = getArguments().getInt("action");
        getLocationDict();
    }


    @Override
    public void initView(View view) {


        mRlUserIcon = view.findViewById(R.id.rl_user_icon);
        mRlFriendIcon = view.findViewById(R.id.rl_friend_icon);
        mRlNickname = view.findViewById(R.id.rl_nickname);
        mRlWid = view.findViewById(R.id.rl_wid);
        mRlBirth = view.findViewById(R.id.rl_birth);
        mRlSex = view.findViewById(R.id.rl_sex);
        mRlRealarea = view.findViewById(R.id.rl_realarea);
        mRlIndustryClass = view.findViewById(R.id.rl_industry_class);
        mRlTags = view.findViewById(R.id.rl_tags);
        mBtnSave = (Button) view.findViewById(R.id.btn_save);

        mRlUserIcon.setOnClickListener(this);
        mRlFriendIcon.setOnClickListener(this);
        mRlNickname.setOnClickListener(this);
        mRlWid.setOnClickListener(this);
        mRlBirth.setOnClickListener(this);
        mRlSex.setOnClickListener(this);
        mRlRealarea.setOnClickListener(this);
        mRlIndustryClass.setOnClickListener(this);
        mRlTags.setOnClickListener(this);
        mBtnSave.setOnClickListener(this);


        mIvUser = (ImageView) view.findViewById(R.id.iv_user);
        mIvFriend = (ImageView) view.findViewById(R.id.iv_friend);
        mTvNickname = (TextView) view.findViewById(R.id.tv_nickname);
        mTvWid = (TextView) view.findViewById(R.id.tv_wid);
        mTvRealarea = (TextView) view.findViewById(R.id.tv_realarea);
        mTvSex = (TextView) view.findViewById(R.id.tv_sex);
        mTvBirth = (TextView) view.findViewById(R.id.tv_birth);
        mTvIndustryClass = (TextView) view.findViewById(R.id.tv_industry_class);
        mTvTags = (TextView) view.findViewById(R.id.tv_tags);

        mBtnSave.setOnClickListener(this);

        BaseActivity baseActivity = (BaseActivity) getActivity();

        if (action == ACTION_CREATE) {//新增
            ImageLoader.getInstance().displayImage(mMediaAccount.getLogo(), mIvUser);
            if (!TextUtils.isEmpty(mMediaAccount.getName())) {
                mTvNickname.setText(mMediaAccount.getName());
            }
            if (!TextUtils.isEmpty(mMediaAccount.getUsername())) {
                mTvWid.setText(mMediaAccount.getUsername());
            }
            mTvSex.setText(mMediaAccount.getGender() == User.CODE_MALE ? "男" : "女");
            isEditable = true;
            baseActivity.setActionBarTitle("新增微信朋友圈账号");
        } else if (action == ACTION_UPDATE) {//更新
            loadWechatInfo(mMediaAccount.getId());
            isEditable = false;
            baseActivity.setActionBarTitle("编辑微信朋友圈账号");
        }


    }


    @Override
    public void onResume() {
        super.onResume();
        MobclickAgent.onPageStart(MEDIA_ADD_RESULT_SCREEN);
        MobclickAgent.onResume(getActivity());

    }

    @Override
    public void onPause() {
        super.onPause();
        MobclickAgent.onPageEnd(MEDIA_ADD_RESULT_SCREEN);
        MobclickAgent.onPause(getActivity());

    }


    @Override
    public void onClick(View v) {
        int id = v.getId();
        switch (id) {
            case R.id.rl_user_icon://用户头像
                if (!isEditableALL) return;
                UIHelper.showIconSelect(this, REQUEST_WECHAT_ICON, mMediaAccount.getLogo());

                break;
            case R.id.rl_friend_icon://上传好友数
                if (!isEditableALL) return;
                String imgPath = "";
                List<String> list = mMediaAccount.getFriendsScreenshot();
                if (list != null && !list.isEmpty()) {
                    imgPath = list.get(0);
                }

                UIHelper.showFriendNumSelect(this, REQUEST_FRIEND, mMediaAccount.getFriends() + "",
                        imgPath);
                break;
            case R.id.rl_sex://性别
                if (!isEditableALL) return;
                genderSelect();
                break;
            case R.id.rl_wid://微信号+截图
                if (!isEditableALL) return;
                UIHelper.showWidChange(this, REQUEST_WID_CHANGE, mTvWid.getText().toString(), mMediaAccount.getProfileScreenshot(), isEditable);
                break;
            case R.id.rl_nickname://微信昵称
                if (!isEditableALL) return;
                UIHelper.showWechatNickname(this, REQUEST_WECHAT_NICKNAME_CHANGE, mTvNickname.getText().toString());
                break;
            case R.id.rl_tags://兴趣标签
                if (!isEditableALL) return;
                UIHelper.showTags(this, REQUEST_INTEREST, SelectTagFragment.CATALOG_INTEREST, mMediaAccount.getTags());
                break;
            case R.id.rl_industry_class://行业分类
                if (!isEditableALL) return;
                Tag tag = mMediaAccount.getIndustry();
                List<Tag> tags = new ArrayList<>();
                if (tag != null) {
                    tags.add(tag);
                }
                UIHelper.showTags(this, REQUEST_INDUSTRY, SelectTagFragment.CATALOG_INDUSTRY, tags);
                break;
            case R.id.rl_birth:
                if (!isEditableALL) return;

                dateSelect();
                break;

            case R.id.rl_realarea:
                if (!isEditableALL) return;

                showAreaSelector();
                break;
            case R.id.btn_save:
                if (!prepareSubmit()) {
                    return;
                }
                showWaitDialog();
                WechatPost post = buildPost();
                if (action == ACTION_UPDATE) {
                    update(mMediaAccount.getId(), post);
                } else if (action == ACTION_CREATE) {
                    create(post);
                }


                break;
        }
    }


    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (data == null) return;

        if (requestCode == REQUEST_INDUSTRY) {//选择行业
            List<Tag> list = (List<Tag>) data.getSerializableExtra(SelectTagFragment.RESPONSE);
            if (list != null && list.size() > 0) {
                mMediaAccount.setIndustry(list.get(0));
                mTvIndustryClass.setText(list.get(0).getName());
            }
        } else if (requestCode == REQUEST_INTEREST) {//兴趣标签
            List<Tag> list = (List<Tag>) data.getSerializableExtra(SelectTagFragment.RESPONSE);

            if (list != null && list.size() > 0) {
                mMediaAccount.setTags(list);
                mTvTags.setText(list.get(0).getName() + "...");
            }
        } else if (requestCode == REQUEST_FRIEND) {//上传好友
            String friendIcon = data.getStringExtra(AddFriendNumFragment.ICON_PATH);
            int friendNum = data.getIntExtra(AddFriendNumFragment.VALUE_NUM, 0);
            ArrayList<String> list = new ArrayList<>();
            list.add(friendIcon);

            mMediaAccount.setFriendsScreenshot(list);
            mMediaAccount.setFriends(friendNum);
            ImageLoader.getInstance().displayImage(friendIcon, mIvFriend);
            mTvFriendTip.setText(Html.fromHtml("上传好友数 (<font color=#f94848>" + friendNum + "</font>)"));
        } else if (requestCode == REQUEST_WID_CHANGE) {//修改微信号
            String name = data.getStringExtra(ChangeWidFragment.VALUE_NAME);
            String profileIcon = data.getStringExtra(ChangeWidFragment.VALUE_WECHAT_NAME_SCREENSHOT);
            mMediaAccount.setUsername(name);
            mTvWid.setText(name);
            mMediaAccount.setProfileScreenshot(profileIcon);
        } else if (requestCode == REQUEST_WECHAT_NICKNAME_CHANGE) {//修改用户昵称
            String username = data.getStringExtra(ChangeWechatNicknameFragment.VALUE_USERNAME);
            mMediaAccount.setName(username);
            mTvNickname.setText(username);
        } else if (requestCode == REQUEST_WECHAT_ICON) {//修改头像
            String icon = data.getStringExtra(AddIconFragment.ICON_PATH);
            if (!TextUtils.isEmpty(icon)) {
                ImageLoader.getInstance().displayImage(icon, mIvUser);
                mMediaAccount.setLogo(icon);
            }

        }


    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        return super.onOptionsItemSelected(item);
    }

    private void initAreaSelector(ArrayList<AddressPicker.Province> areas) {
        if (mAddressPicker == null) {
            mAddressPicker = new AddressPicker(getActivity(), areas);
            mAddressPicker.setOnAddressPickListener((province, city, county) -> {
                StringBuilder sb = new StringBuilder();
                if (province != null) {
                    MediaAccount.Area area = new MediaAccount.Area(province.getAreaId(), province.getName());
                    mMediaAccount.setLocation1(area);
                    sb.append(area.getName());
                }

                if (city != null) {
                    MediaAccount.Area area = new MediaAccount.Area(city.getAreaId(), city.getName());
                    mMediaAccount.setLocation2(area);
                    sb.append("-").append(area.getName());

                } else {
                    mMediaAccount.setLocation2(mMediaAccount.getLocation1());
                }

                if (county != null) {
                    MediaAccount.Area area = new MediaAccount.Area(county.getAreaId(), county.getName());
                    mMediaAccount.setLocation3(area);
                    sb.append("-").append(area.getName());
                } else {
                    if (mMediaAccount.getLocation2() != null) {
                        mMediaAccount.setLocation3(mMediaAccount.getLocation2());
                    } else {
                        mMediaAccount.setLocation3(mMediaAccount.getLocation1());
                    }

                }

                mTvRealarea.setText(sb.toString());

            });

        }

    }

    private void showAreaSelector() {
        try {
            if (mAddressPicker != null) {
                mAddressPicker.show();
            } else {
                AppContext.showToast("请稍候再试");
            }
        } catch (Exception e) {
            e.printStackTrace();
            AppContext.showToast("请稍后再试");
        }

    }

    private void dateSelect() {
        DatePicker picker = new DatePicker(getActivity(), DatePicker.YEAR_MONTH_DAY);
        picker.setRange(1900, Calendar.getInstance().get(Calendar.YEAR));
        picker.setSelectedItem(1980, 1, 1);
        picker.setOnDatePickListener(new DatePicker.OnYearMonthDayPickListener() {
            @Override
            public void onDatePicked(String year, String month, String day) {
                String date = String.format("%s-%s-%s", year, month, day);
                mTvBirth.setText(date);
                mMediaAccount.setBirthday(date);
            }
        });

        picker.show();
    }


    private void genderSelect() {
        OptionPicker picker = new OptionPicker(getActivity(), new String[]{"男", "女"});
        picker.setOnOptionPickListener(new OptionPicker.OnOptionPickListener() {
            @Override
            public void onOptionPicked(int position, String option) {
                mTvSex.setText(option);
                int gender = option.equals("男") ? User.CODE_MALE : User.CODE_FAMALE;
                mMediaAccount.setGender(gender);
            }
        });

        picker.show();
    }


    private void getLocationDict() {
        showWaitDialog();
        ApiFactory.getUserApi().getLocationList().subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new BaseSubscriber<Result<ArrayList<AddressPicker.Province>>>(getActivity()) {
                    @Override
                    public void onCompleted() {
                        hideWaitDialog();

                    }

                    @Override
                    public void onNext(Result<ArrayList<AddressPicker.Province>> listResult) {
                        super.onNext(listResult);
                        if (listResult.getData() != null && !listResult.getData().isEmpty()) {
                            initAreaSelector(listResult.getData());
                        }

                    }

                    @Override
                    public void onError(Throwable e) {
                        super.onError(e);
                        e.printStackTrace();
                        hideWaitDialog();
                    }
                });
    }


    private boolean prepareSubmit() {
        if (mMediaAccount.getFriendsScreenshot() == null || mMediaAccount.getFriendsScreenshot().isEmpty()) {
            AppContext.showToast("请上传好友数截图");
            return false;
        }
        if (mTvNickname.getText().toString().isEmpty()) {
            AppContext.showToast("用户昵称未填写");
            return false;
        }
        if (mTvBirth.getText().toString().isEmpty()) {
            AppContext.showToast("请选择出生日期");
            return false;
        }
        if (mTvSex.getText().toString().isEmpty()) {
            AppContext.showToast("请选择性别");
            return false;
        }

        if (mTvRealarea.getText().toString().isEmpty()) {
            AppContext.showToast("请选择地区");
            return false;
        }

        if (mTvTags.getText().toString().isEmpty()) {
            AppContext.showToast("请选择标签");
            return false;
        }

        if (mTvIndustryClass.getText().toString().isEmpty()) {
            AppContext.showToast("请选择行业分类");
            return false;
        }
        return true;
    }

    private String[] tagToId(List<Tag> tags) {
        ArrayList<String> ids = new ArrayList<>();
        for (Tag tag : tags) {
            ids.add(tag.getId());
        }
        return ids.toArray(new String[ids.size()]);
    }


    private void update(String mediaid, WechatPost post) {
        ApiFactory.getUserApi().updateWechatAccount(mediaid, post).subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new BaseSubscriber<Result>(getActivity()) {
                    @Override
                    public void onCompleted() {
                        super.onCompleted();
                        hideWaitDialog();
                        EventBus.getDefault().post(new MediaChangeEvent(MediaChangeEvent.EVENT_MEDIA_UPDATE, null));

                    }

                    @Override
                    public void onNext(Result result) {
                        AppContext.showToast("更新成功");
                        getActivity().finish();
                        hideWaitDialog();
                    }

                    @Override
                    public void onError(Throwable e) {
                        super.onError(e);
                        AppContext.showToast(e.getMessage());
                        hideWaitDialog();

                    }
                });
    }


//    private void notifyMain() {
//        Intent intent = new Intent(AppConstant.INTENT_ACTION_MEDIA_ADD);
//        getActivity().sendBroadcast(intent);
//    }


    private void create(WechatPost post) {
        ApiFactory.getUserApi().addWechatAccount(post).subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new BaseSubscriber<Result>(getActivity()) {
                    @Override
                    public void onCompleted() {
                        super.onCompleted();
                        AppContext.showToast("成功");
                        EventBus.getDefault().post(new MediaChangeEvent(MediaChangeEvent.EVENT_MEDIA_ADD, null));

//                        notifyMain();
                        AppContext.setMeidaAccount(true);


                        CommonDialog dialog = new CommonDialog(getActivity());
                        dialog.setMessage(getResources().getString(R.string.dialog_register_wechat));
                        dialog.setPositiveButton("确定", new DialogInterface.OnClickListener() {

                            @Override
                            public void onClick(DialogInterface arg0, int arg1) {
                                dialog.dismiss();
                                getActivity().finish();
                                hideWaitDialog();
                            }
                        });

                        dialog.show();

                    }

                    @Override
                    public void onNext(Result result) {
                        super.onNext(result);
                        AppContext.setMeidaAccount(true);

                    }

                    @Override
                    public void onError(Throwable e) {
                        super.onError(e);
                        if (e instanceof ApiException) {
                            ApiException exception = (ApiException) e;
                            if (exception.getErrorCode() == ApiErrorCode.ERROR_PARAM_CHECK || exception.getErrorCode() == ApiErrorCode.ERROR_REQUEST_PARAM) {
                                ApiErrorHelper.showErrorDetail(exception.getExtendErrorMsg());
                            }

                        }
                        hideWaitDialog();

                    }
                });

    }

    @NonNull
    private WechatPost buildPost() {
        WechatPost.Post wechatPost = new WechatPost.Post(mMediaAccount.getLogo(),
                mMediaAccount.getFriends(),
                mMediaAccount.getFriendsScreenshot(),
                mMediaAccount.getName(),
                mMediaAccount.getUsername(),
                mMediaAccount.getProfileScreenshot(),
                mMediaAccount.getBirthday(),
                mMediaAccount.getGender(),
                mMediaAccount.getLocation1().getId(),
                mMediaAccount.getLocation2().getId(),
                mMediaAccount.getLocation3().getId(),
                mMediaAccount.getIndustry().getId(),
                tagToId(mMediaAccount.getTags()),
                mMediaAccount.getOpenid(),
                mMediaAccount.getUnionid());

        return new WechatPost(wechatPost);
    }


    private void loadWechatInfo(String id) {
        showWaitDialog();
        ApiFactory.getUserApi().getWechatAccountInfo(id).subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new BaseSubscriber<Result<MediaAccount>>(getActivity()) {
                    @Override
                    public void onCompleted() {
                        hideWaitDialog();
                    }

                    @Override
                    public void onNext(Result<MediaAccount> mediaAccountResult) {
                        mMediaAccount = mediaAccountResult.getData();
                        if (mMediaAccount == null) return;
                        if (mMediaAccount.getStatus() == MediaAccount.STATE_NEW) {
                            isEditableALL = false;
                        }
                        if (mMediaAccount.getStatus() == MediaAccount.STATE_INACTIVE || mMediaAccount.getStatus() == MediaAccount.STATE_REGECTED) {
                            isEditable = true;
                        } else {
                            isEditable = false;
                        }
                        fillUI();

                    }

                    @Override
                    public void onError(Throwable e) {
                        super.onError(e);
                        e.printStackTrace();
                        hideWaitDialog();
                    }
                });
    }


    private void fillUI() {
        ImageLoader.getInstance().displayImage(mMediaAccount.getLogo(), mIvUser);
        if (!mMediaAccount.getFriendsScreenshot().isEmpty())
            ImageLoader.getInstance().displayImage(mMediaAccount.getFriendsScreenshot().get(0), mIvFriend);
        mTvNickname.setText(mMediaAccount.getName());
        mTvWid.setText(mMediaAccount.getUsername());
        mTvBirth.setText(mMediaAccount.getBirthday());
        mTvSex.setText(mMediaAccount.getGender() == User.CODE_FAMALE ? "女" : "男");
        StringBuilder sb = new StringBuilder("");
        for (Tag tag : mMediaAccount.getTags()) {
            sb.append(tag.getName()).append(",");
        }

        mTvTags.setText(sb.toString());


        sb = new StringBuilder("");
        MediaAccount.Area area = mMediaAccount.getLocation1();
        if (area != null) {
            sb.append(area.getName());
        }
        area = mMediaAccount.getLocation2();
        if (area != null) {
            sb.append("-").append(area.getName());
        }
        area = mMediaAccount.getLocation3();
        if (area != null) {
            sb.append("-").append(area.getName());
        }

        mTvRealarea.setText(sb.toString());
        mTvFriendTip.setText(Html.fromHtml("上传好友数 (<font color=#f94848>" + mMediaAccount.getFriends() + "</font>)"));
        mTvIndustryClass.setText(mMediaAccount.getIndustry().getName());

    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        ButterKnife.unbind(this);
    }
}
